package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ev.asl.constant.AslConstant;
import com.ev.framework.utils.JSONUtils;
import com.ev.framework.utils.MD5Utils;
import com.ev.framework.utils.R;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3UserSynService;
import com.ev.k3cloudBusiness.vo.K3DeeSyncVO;
import com.ev.k3cloudBusiness.vo.K3MaterialResultsVo;
import com.ev.k3cloudBusiness.vo.K3UserResultsVO;
import com.ev.system.domain.DeptDO;
import com.ev.system.domain.UserDO;
import com.ev.system.service.DeptService;
import com.ev.system.service.UserService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 姚家乐
 * @since 2021/6/1 9:21
 */
@Service
@Slf4j
public class K3UserSynServiceImpl implements K3UserSynService {
    private static final String      PASSWORD = "111111";

    @Autowired
    private kingdeeMiddlewareService kingdeeMiddlewareService;

    @Autowired
    private UserService              userService;

    @Autowired
    private DeptService              deptService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R userSync() {
        //查询芯软云用户
        List<UserDO> userDOList = userService.listAll();
        String userResult = kingdeeMiddlewareService.UserAll();
        K3DeeSyncVO<List<K3UserResultsVO>> kingdeeSyncVO = new Gson().fromJson(userResult,new TypeToken<K3DeeSyncVO<List<K3UserResultsVO>>>(){}.getType());

        if(!AslConstant.ZERO.equals(kingdeeSyncVO.getCode()))
        {
            log.info(kingdeeSyncVO.getMsg());
            return  R.error(kingdeeSyncVO.getMsg());
        }
        List<K3UserResultsVO> k3UserResultsVOS = kingdeeSyncVO.getData();

        if (k3UserResultsVOS.size() == 0) {
            log.info("K3Cloud无可同步用户");
            return R.error("K3Cloud无可同步用户");
        }

        k3UserResultsVOS.removeIf(e -> e.getDepartmentId() == null);
        k3UserResultsVOS.forEach(e -> {
            if (e.getDepartmentId() == 0) {
                e.setDepartmentId(1L);
            }
        });
        List<Long> remoteDeptIdList = k3UserResultsVOS.stream()
            .map(K3UserResultsVO::getDepartmentId).distinct().collect(Collectors.toList());

        // 获取全部部门
        List<DeptDO> deptDOList = deptService.listForAll();
        List<Long> localDeptIdList = deptDOList.stream().map(DeptDO::getDeptId)
            .collect(Collectors.toList());
        remoteDeptIdList.removeAll(localDeptIdList);

        // 本地用户id
        List<String> localIdList = userDOList.stream().map(UserDO::getUsername)
            .collect(Collectors.toList());
        // K3Cloud用户id
        List<String> remoteIdList = k3UserResultsVOS.stream().map(K3UserResultsVO::getName)
            .collect(Collectors.toList());
        // 删除的 k3无，本地有
        List<String> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e))
            .collect(Collectors.toList());
        // 修改的（本地库有的，远端库有的）
        List<String> updateIdList = remoteIdList.stream().filter(localIdList::contains)
            .collect(Collectors.toList());
        // 新增的（本地库无的，远端库有的）
        remoteIdList.removeAll(updateIdList);

        UserDO userDO;
        List<UserDO> updateUserDOList = Lists.newArrayList();
        // 将账号设置为禁用
        if (deleteIdList.size() > 0) {
            deleteIdList.removeIf(e -> Objects.equals(e, "admin"));
            List<UserDO> updateList = userDOList.stream()
                .filter(e -> deleteIdList.contains(e.getUsername())).collect(Collectors.toList());
            updateList.forEach(e -> e.setStatus(0));
            updateUserDOList.addAll(updateList);
        }
        // 不可更改账号名
        if (updateIdList.size() > 0) {
            List<K3UserResultsVO> updateList = k3UserResultsVOS.stream()
                .filter(e -> updateIdList.contains(e.getName())).collect(Collectors.toList());
            for (K3UserResultsVO kingdeeUserSyncVO : updateList) {
                userDO = new UserDO();
                // 更改部门ID
                userDO.setUserId(kingdeeUserSyncVO.getUserId());
                userDO.setName(kingdeeUserSyncVO.getName());
                userDO.setUsername(kingdeeUserSyncVO.getName());
                userDO.setEmployeeId(kingdeeUserSyncVO.getEmpId());
                userDO.setDeptId(kingdeeUserSyncVO.getDepartmentId());
                updateUserDOList.add(userDO);
            }
        }
        if (updateUserDOList.size() > 0) {
            //批量修改
//            userService.batchUpdate(updateUserDOList);
        }

        if (remoteIdList.size() > 0) {
            List<K3UserResultsVO> saveList = k3UserResultsVOS.stream()
                .filter(e -> remoteIdList.contains(e.getName())).collect(Collectors.toList());
            List<UserDO> saveUserDOList = Lists.newArrayList();
            for (K3UserResultsVO kingdeeUserSyncVO : saveList) {
                userDO = new UserDO();
                String name = kingdeeUserSyncVO.getName();
                userDO.setName(name);
                userDO.setUsername(name);
                userDO.setDeptId(kingdeeUserSyncVO.getDepartmentId());
//                userDO.setUserId(kingdeeUserSyncVO.getUserId());
                userDO.setEmployeeId(kingdeeUserSyncVO.getUserId());
                userDO.setPassword(MD5Utils.encrypt(name, PASSWORD));
                userDO.setStatus(1);
                saveUserDOList.add(userDO);
            }
            // 批量保存
            userService.batchSaveHaveId(saveUserDOList);
        }
        return R.ok();
    }
}
